package com.github.live.component;

import android.content.Context;
import android.content.res.TypedArray;
import android.os.Handler;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.github.live.R;
import com.github.live.manager.ChannelsManager;
import com.github.live.manager.EpgManager;
import com.github.live.base.VisibleComponent;
import com.github.live.manager.LiveInitializer;
import com.github.livebase.bean.Channel;
import com.github.livebase.bean.EpgInformation;
import com.github.livebase.event.Event;
import com.github.livebase.event.EventBus;
import com.github.livebase.event.EventListener;
import com.github.livebase.event.SimpleEventBus;

import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * @ClassName EpgInfoFragment
 * @description: 底部Epg信息
 * @author: biao532
 * @create: 2023-12-07 22:32
 * @Version 1.0
 **/
public class ChannelInfoView extends LinearLayout implements EventListener, VisibleComponent {
    // Bottom Channel View
    private ImageView logo;
    private TextView tv_sys_time;
    private TextView tv_size;
    private TextView tv_source;
    // Bottom Channel View - Line 1 / 2 / 3
    private TextView tv_channelname;
    private TextView tv_channelnum;
    private TextView tv_curr_name;
    private TextView tv_curr_time;
    private TextView tv_next_name;
    private TextView tv_next_time;
    private LinearLayout llSeekBar;
    private TextView mCurrentTime;
    private SeekBar mSeekBar;
    private TextView mTotalTime;
    private Handler mHandler;
    private EpgManager epgManager;
    private WeakReference<ChannelInfoView> _this = new WeakReference<>(this);
    private Runnable mHideRun = new Runnable() {
        @Override
        public void run() {
            ChannelInfoView __this = _this.get();
            if (__this == null) {
                return;
            }
            if (!__this.isShowing()) {
                return;
            }
            __this.setVisibility(View.GONE);
        }
    };
    private SimpleDateFormat simpleDateFormat;
    public ChannelInfoView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        TypedArray attrsArray = context.obtainStyledAttributes(attrs, R.styleable.EpgInfoView);
        String format = attrsArray.getString(R.styleable.EpgInfoView_timeFormat);
        if (TextUtils.isEmpty(format)) {
            format = "hh:mm aa";
        }
        simpleDateFormat = new SimpleDateFormat(format, Locale.ENGLISH);
        init(context);
    }

    public ChannelInfoView(Context context) {
        super(context);
        init(context);
    }

    public void setHandler(Handler mHandler) {
        this.mHandler = mHandler;
    }

    protected void init(Context context) {
        LayoutInflater.from(context).inflate(R.layout.component_epginfo, this);
        logo = findViewById(R.id.tv_logo);
        tv_curr_time = findViewById(R.id.tv_current_program_time);
        tv_curr_name = findViewById(R.id.tv_current_program_name);
        tv_next_time = findViewById(R.id.tv_next_program_time);
        tv_next_name = findViewById(R.id.tv_next_program_name);
        tv_channelname = findViewById(R.id.tv_channel_name);  //底部名称
        tv_channelnum = findViewById(R.id.tv_channel_number); //底部数字
        tv_size = findViewById(R.id.tv_size);                 // Resolution
        tv_source = findViewById(R.id.tv_source);             // Source/Total Source
        tv_sys_time = findViewById(R.id.tv_sys_time);         // System Time
        llSeekBar = findViewById(R.id.ll_seekbar);
        mCurrentTime = findViewById(R.id.curr_time);
        mSeekBar = findViewById(R.id.seekBar);
        mTotalTime = findViewById(R.id.total_time);
        epgManager = LiveInitializer.getInitializer()
                .getEpgManager();
        mSeekBar.setFocusable(true);
        mSeekBar.setClickable(true);
        setDate(new Date());

        SimpleEventBus.getDefault().register(EventBus.EVENT_CHANGE_TIME, this, false);
    }

    public void setOnSeekBarChangeListener(SeekBar.OnSeekBarChangeListener listener) {
        mSeekBar.setOnSeekBarChangeListener(listener);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_UP) {
            return false;
        }
        if (mSeekBar.getVisibility() != VISIBLE) {
            return dispatchKeyEvent(event);
        }
        int keyCode = event.getKeyCode();
        switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_UP:
            case KeyEvent.KEYCODE_DPAD_RIGHT:
            case KeyEvent.KEYCODE_DPAD_LEFT:
            case KeyEvent.KEYCODE_DPAD_DOWN:
                super.dispatchKeyEvent(event);
                return true;
        }
        return false;
    }

    @Override
    public void show() {
        if (isShowing()) {
            mHandler.removeCallbacks(mHideRun);
            return;
        }
        setVisibility(VISIBLE);
    }

    @Override
    public void hide(long delay) {
        mHandler.removeCallbacks(mHideRun);
        mHandler.postDelayed(mHideRun, delay);
    }

    public void showProgress(long maxDuration) {
        llSeekBar.setVisibility(View.VISIBLE);
        maxDuration = maxDuration / 1000;
        mSeekBar.setMax((int) maxDuration);
        mSeekBar.setKeyProgressIncrement((int) (maxDuration / 100));
        mTotalTime.setText(stringForTimeVod(maxDuration));
    }
    public void updateCurrentProgress(long duration) {
        duration = duration / 1000;
        mSeekBar.setProgress((int) duration);
        duration++;
        if (duration > mSeekBar.getMax()) {
            duration = mSeekBar.getMax();
        }
        mCurrentTime.setText(stringForTimeVod(duration));
    }
    private String stringForTimeVod(long position) {
        long h = position / 3600;
        position = position % 3600;
        long m = position / 60;
        long s = position % 60;
        return String.format("%s:%s:%s", f(h), f(m), f(s));
    }

    public long computeProgress(long duration) {
        return (duration * mSeekBar.getProgress()) / mSeekBar.getMax();
    }
    public void hideProgress() {
        llSeekBar.setVisibility(View.GONE);
    }
    public void setSize(int width, int height) {
        tv_size.setText(width + " x " + height);
    }
    public void updateEpgInformation(EpgInformation current, EpgInformation next) {
        if (current != null) {
            tv_curr_time.setText(current.getStartString() + " - " + current.getEndString());
            tv_curr_name.setText(current.getTitle());
        }
        if (next != null) {
            tv_next_time.setText(next.getStartString() + " - " + next.getEndString());
            tv_next_name.setText(next.getTitle());
        }
    }

    private void updateEpgInformation() {
        ChannelsManager cm = LiveInitializer.getInitializer().getChannelsManager();
        Channel s = cm.getCurrentChannel();
        if (cm.isLive()) {
            updateEpgInformation(epgManager.getCurrentEpgInfo(s), epgManager.getNextEpgInfo(s));
        }
        else {
            updateEpgInformation(null, epgManager.getCurrentEpgInfo(s));
        }
    }


    public void setCurrentChannel(Channel newChannel) {
        tv_channelname.setText(newChannel.getName());
        tv_channelnum.setText("" + newChannel.getNumber());
        updateEpgInformation(epgManager.getCurrentEpgInfo(newChannel), epgManager.getNextEpgInfo(newChannel));
        renderTvLogo(newChannel.getLogo());
    }
    public void setSourceInfo(int current, int allSize) {
        if (allSize <= 0) {
            tv_source.setText("1/1");
        } else {
            tv_source.setText("线路 " + (current + 1) + "/" + allSize);
        }
    }

    protected void setDate(Date date) {
        tv_sys_time.setText(simpleDateFormat.format(date));
    }
    private String f(long t) {
        if (t < 0) {
            return "00";
        }
        if (t < 10) {
            return "0" + t;
        }
        return String.valueOf(t);
    }

    // Get Channel Logo
    private void renderTvLogo(String logoPath) {
        Glide.with(getContext()).load(logoPath)
                //.fitCenter()
                //.skipMemoryCache(true)
                .diskCacheStrategy(DiskCacheStrategy.RESULT)
                .dontAnimate()
                .placeholder(R.color.transparent)
                .error(R.drawable.img_logo_placeholder)
                .into(logo);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        SimpleEventBus.getDefault().unregister(EventBus.EVENT_CHANGE_TIME, this);
    }

    @Override
    public void onEvent(Event event) {
        if (!Event.isEvent(event, EventBus.EVENT_CHANGE_TIME)) {
            return;
        }
        this.setDate(event.getAttachObject());
        this.updateEpgInformation();
    }
}